import * as apis from '@/apis/modules/deviceManage.js';

const deviceManage = {
	namespaced: true,
	state: {
		list: [],
		total: 0,
		installedNum: 0,
		hasData: true,
		pageNum: 1,
		detail: {}
	},
	mutations: {
		save(state, {field, payload}) {
		  if (Object.prototype.toString.call(payload) === '[object Object]') {
			state[field] = { ...state[field], ...payload }
		  } else {
			state[field] = payload
		  }
		}
	},
	actions: {
		 getStatistics({ commit }, deviceType = '00') {
			 apis.getStatistics(deviceType)
				.then(({error, data}) => {
					if (error) return
					
					const {inStorage, installed} = data
					
					commit('save', {field: 'total', payload: inStorage})
					commit('save', {field: 'installedNum', payload: installed})
				})
		},
		
		getList({ commit, state }, {deviceType = '00', pageNum = 1, search = ''} = {}) {
			apis.getList({deviceType, current: pageNum, size: 10, search})
				.then(({error, data}) => {
					if (error) return
					
					const {pages, records} = data
					const {list} = state
					let recordList = list
					
					if (pageNum > 1) {
						recordList = recordList.concat(records)
					} else {
						recordList = records || []
						commit('save', {field: 'hasData', payload: true})
					}
					
					if (pages === pageNum || pages === 0) commit('save', {field: 'hasData', payload: false})
					
					commit('save', {field: 'pageNum', payload: pageNum})
					commit('save', {field: 'list', payload: recordList})
				})
		},
	}
}

export default deviceManage